#include "widget.h"
#include "./ui_widget.h"
#include <QMimeData>
#include <QFileInfo>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setAcceptDrops(true);
    ui->plainTextEdit->setAcceptDrops(false);
    ui->label->setAcceptDrops(false);
    ui->label->setScaledContents(true); // 根据大小缩放内容
}

Widget::~Widget()
{
    delete ui;
}

void Widget::resizeEvent(QResizeEvent *event)
{
    QSize size = ui->plainTextEdit->size();
    ui->plainTextEdit->move(5, 5);
    ui->label->move(5, size.height() + 10);
    ui->plainTextEdit->resize(this->width() - 10, size.height());
    ui->label->resize(this->width() - 10, this->height() - size.height() - 20);
    event->accept();
}

void Widget::dragEnterEvent(QDragEnterEvent *event)
{
    ui->plainTextEdit->clear();
    ui->plainTextEdit->appendPlainText("dragEnterEvent事件, mimeData的formats:");
    for (auto &item : event->mimeData()->formats()) {
        ui->plainTextEdit->appendPlainText(item);
    }

    ui->plainTextEdit->appendPlainText("dragEnterEvent事件, mimeData的urls:");
    for (auto &item : event->mimeData()->urls()) {
        ui->plainTextEdit->appendPlainText(item.toString());
    }

    if (event->mimeData()->hasUrls()) {
        QString fileName = event->mimeData()->urls()[0].fileName();
        QFileInfo fileInfo(fileName);
        QString suffix = fileInfo.suffix().toUpper();
        if (suffix == "JPG") {
            event->acceptProposedAction(); // 接收这个东西进门
        }
        else {
            event->ignore();
        }
    }
    else {
        event->ignore();
    }
}

void Widget::dropEvent(QDropEvent *event)
{
    QString fullpath = event->mimeData()->urls()[0].path();
#ifdef WIN32
    // 该路径为posix name 风格, 即第一个字符为"/". 对于Windows OS, 需要去掉
    fullpath = fullpath.right(fullpath.length() - 1);
#endif

    QPixmap pixmap(fullpath);
    ui->label->setPixmap(pixmap);
    event->accept();
}
